<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <!--参考https://www.jb51.net/article/178607.htm-->
    <title>Title</title>

    <link href="{{url_for('static',filename='css/style.default.css',_external=True)}}" rel="stylesheet">
    <link href="{{url_for('static',filename='css/select2.css',_external=True)}}" rel="stylesheet" />
    <link href="{{url_for('static',filename='css/style.datatables.css',_external=True)}}" rel="stylesheet">
    <link href="{{url_for('static',filename='css/datatables.responsive.css',_external=True)}}" rel="stylesheet">

    <script src="{{url_for('static',filename='js/jquery-1.11.1.min.js',_external=True)}}"></script>
    <script src="{{url_for('static',filename='js/jquery-migrate-1.2.1.min.js',_external=True)}}"></script>
    <script src="{{url_for('static',filename='js/bootstrap.min.js',_external=True)}}"></script>
    <script src="{{url_for('static',filename='js/modernizr.min.js',_external=True)}}"></script>
    <script src="{{url_for('static',filename='js/pace.min.js',_external=True)}}"></script>
    <script src="{{url_for('static',filename='js/retina.min.js',_external=True)}}"></script>
    <script src="{{url_for('static',filename='js/jquery.cookies.js',_external=True)}}"></script>

    <script src="{{url_for('static',filename='js/jquery.datatables.min.js',_external=True)}}"></script>
    <script src="{{url_for('static',filename='js/vue.js',_external=True)}}"></script>
    <script src="{{url_for('static',filename='js/axios.min.js',_external=True)}}"></script>
    <script src="https://cdn.plot.ly/plotly-2.4.2.min.js"></script>

    <style>
         #showTime
         {
          width: 300px;
          height: 60px;
          font-size: 60px;
          line-height: 60px;
         }

          *{margin:0;padding:0;}

        /*参考https://jingyan.baidu.com/article/f3ad7d0fa974c749c3345bff.html*/
        /*.circle{*/
            /*border: 1px solid #3db8da;*/
            /*width:120px;*/
            /*height:120px;*/
            /*border-radius: 60px;*/
        /*}*/

        button {
            margin:10px
        }

        #startBn, #restBn{
             width:50px;
             height:50px;
             background-color:#ffffff;
             border-radius:50%;
             opacity:0.5;
             font-weight:1000
        }

    </style>
</head>
<body>
    <div id="clockControl" class="contentpanel">
        <div class="row">
            <div class="col-sm-4">
                <!--占位符-->
                <div>
                    <div v-for="count in 5" class="row">
                        <div class="col-sm-12">&nbsp;</div>
                    </div>
                    <div style="text-align:center">
                        <label v-text="fatigueState" style="font-size: 40px;color: red">Normal</label>
                    </div>
                    <div v-for="count in 2" class="row">
                        <div class="col-sm-12">&nbsp;</div>
                    </div>
                </div>

                <!--计时器-->
                <div class="row">
                    <div class="col-sm-12">

                        <div class="row">
                            <div style="text-align:center">
                                <label id="showTime" v-text="showTime_v">00:00:00</label>
                            </div>
                        </div>

                        <div class="row">
                            <div style="text-align: center">
                                <!--开始按钮 ~ 暂停按钮-->
                                <input id="startBn" type="button" v-bind:value="startBn_v" v-on:click="clickHandler('startBn'),start_pause_collected()">
                                <!-- 复位(结束) 按钮 -->
                                <input id="restBn" type="button" v-bind:value="restBn_v" v-on:click="clickHandler('restBn'),end_collected()">

                                <!--点击结束按键, 弹出模态框, 用js控制-->
                                <form method="post" action="{{url_for('annotate_Fatigue')}}">
                                    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                                        <div class="modal-dialog" role="document" style="width:750px">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                                    <h4 class="modal-title" id="myModalLabel">节拍响应折线图</h4>
                                                </div>
                                                <div class="modal-body">
                                                    <div class="row">
                                                        <div class="col-sm-12">
                                                            <div id="line-chart"></div>
                                                        </div>
                                                        <div class="col-sm-12" style="text-align: center">
                                                            <label>疲劳状态标注：</label>
                                                            <select name="fatigueState">
                                                                <option value="1">1-极度警醒</option>
                                                                <option value="2">2-非常警醒</option>
                                                                <option value="3">3-警醒</option>
                                                                <option value="4">4-比较警醒</option>
                                                                <option value="5">5-不太警醒但也无困意</option>
                                                                <option value="6">6-有一些困意倾向</option>
                                                                <option value="7">7-有困意，但是不需要努力保持清醒</option>
                                                                <option value="8">8-有困意，且需要一定的努力保持清醒</option>
                                                                <option value="9">9-非常困倦，需要极大的努力保持清醒</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <!--<button type="reset" class="btn btn-default" data-dismiss="modal">重置</button>-->
                                                    <button type="submit" class="btn btn-primary">提交</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

                 <div class="row">
                    <div class="col-sm-12">
                        &nbsp;
                    </div>
                 </div>

                 <div class="row">
                    <div class="col-sm-12" style="text-align:center">
                        <button type="button" class="btn btn-danger btn-circle" title="点击我听A键提示音" v-on:click="music_clickPlay('click1')">A</button>
                        <button type="button" class="btn btn-success btn-circle" title="点击我听S键提示音" v-on:click="music_clickPlay('click2')">S</button>
                        <button type="button" class="btn btn-info btn-circle" title="点击我听D键提示音" v-on:click="music_clickPlay('click3')">D</button>
                    </div>
                </div>

                <!--不显示audio-->
                <div style="display: None;">
                    <!--    参考<https://www.w3school.com.cn/html5/att_audio_autoplay.asp> -->
                    <audio id="click1" controls="controls" autoplay="autoplay">
                        <source src="../static/mp3/click4.mp3" type="audio/mpeg">
                    </audio>

                    <audio id="click2" controls="controls">
                        <source src="../static/mp3/click2.mp3" type="audio/mpeg">
                    </audio>

                    <audio id="click3" controls="controls">
                        <source src="../static/mp3/click3.mp3" type="audio/mpeg">
                    </audio>
                </div>
            </div>
            
            <div class="col-sm-8">
                <div class="panel panel-primary-head">
                    <div class="panel-heading">
                        <h4 class="panel-title">根据不同提示音，按下指定按键</h4>
                        <p>不同提示音对应不同按键(A,S,D)，提示音出现的时间是一个随机数值</p>
                    </div><!-- panel-heading -->

                    <table id="basicTable" class="table table-striped table-bordered responsive">
                        <thead class="">
                            <tr>
                                <th>节拍开始时间</th>
                                <th>节拍要求键入</th>
                                <th>节拍响应时间</th>
                                <th>节拍实际键入</th>
                            </tr>
                        </thead>

                        <tbody>
                            <tr v-for="(row,index) in beat_startT">
                                <td v-text="beat_startT[index]"></td>
                                <td v-text="beat_key[index]"></td>
                                <td v-text="beat_resT[index]"></td>
                                <td v-text="beat_resKey[index]">61</td>
                            </tr>
                        </tbody>
                    </table>
                </div><!-- panel -->
            </div>
        </div>
    </div>

    <script>

        var keyPress, beat_table,beat_startT,beat_key,beat_resKey,beat_resT
        var save_video_flag = false
        document.onkeydown = function(e) {
            let key = window.event.keyCode;
            if (key == 65) {
                keyPress = 'A'
            }
            else if (key == 83) {
                keyPress = 'S'
            }
            else if (key == 68) {
                keyPress = 'D'
            }

//            alert(keyPress)

            try{
                axios.get("/keyPress/" + keyPress)
                    .then(res => {
                    beat_table = res.data
//                             console.log(res.data)
                console.log(beat_table["beat_startT"])
//
                beat_startT = beat_table["beat_startT"],
                beat_key = beat_table["beat_key"],
                beat_resKey = beat_table["beat_resKey"],
                beat_resT = beat_table["beat_responeT"]
//                             console.log(_this.beat_startT)
//                             console.log(_this.beat_startT[0])
            })
            }catch(err){
                console.log(err);
            }

            //开始采集视频,只请求一次即可，结束采集后会将save_video_flag置为false
            if(save_video_flag == false){
                save_video_flag = true

                try{
                    axios.get("/save_monitor_video/0")
                        .then(res => {
                        console.log(res.data)
                    })
                }catch(err){
                    console.log(err);
                }

//                try{
//                    axios.get("/save_monitor_video/192.168.1.64")
//                        .then(res => {
//                            console.log(res.data)
//                    })
//                }catch(err){
//                    console.log(err);
//                }
            }
        };

       var clockT = new Vue({
           el : "#clockControl",
           data : {
               showTime_v : "00:00:00",
               startBn_v : "开始",
               restBn_v : "结束",
               bool_flag : false,
               pauseTime : 0,
               pauseDate : 0,
               time : 0,

               music_id : "",
               startPress : false,  //True表示点击开始按钮，False表示点击暂停，结束按钮，或者不点击按钮
               endPress : false,  //是否在计时过程中点击结束按钮，用来控制模态框的显示

               keyPress : "",

               beat_table : "",
               beat_table_json : "",
               beat_startT : beat_startT,
               beat_key : beat_key,
               beat_resKey : beat_resKey,
               beat_resT : beat_resT,

               x_array : [],
               y_array : [],
               names : [],

               fatigueState : "Alert state"
           },

           mounted : function () {
               window.setInterval(this.animation,16);
               window.setInterval(this.start_pause_collected,1000);  //每秒向后台请求一次提示音
               window.setInterval(this.key_Pressed_flash,500)
               window.setInterval(this.get_FatigueState,1000)
           },

           methods : {

               /** 数据回显（配合定时器使用）*/
               key_Pressed_flash : function () {
                   this.beat_startT = beat_startT
                   this.beat_key = beat_key
                   this.beat_resKey = beat_resKey
                   this.beat_resT = beat_resT
               },

               /*计时器函数：animation，clickHandler*/
               //转化时间函数
               animation :function() {
                   if(!this.bool_flag) return;
                   //前时间减去上次开启时间减去暂停累计时间
                   var times=new Date().getTime()- this.time- this.pauseTime;
                   var minutes=Math.floor(times/60000);//毫秒转化为分钟
                   var seconds=Math.floor((times-minutes*60000)/1000);//已知分钟
                   //将time减去分钟 除去1000得出 秒
                   var ms=Math.floor((times-minutes*60000-seconds*1000)/10);//
                   this.showTime_v =
                       (minutes<10 ? "0" +minutes : minutes)+":"
                       +(seconds<10 ? "0"+seconds :seconds)+":"
                       +(ms<10 ? "0"+ms : ms);
//                   alert("animation")
                },

               //点击时的事件
               clickHandler : function (buttonType) {
                   if(buttonType==="startBn"){
                       this.bool_flag = !this.bool_flag;
                       if(this.bool_flag){
                           this.startPress = true
                           this.startBn_v = "暂停";
                           //如果我们上一次暂停时间是空，表示没有暂停过，因此，直接返回0
                           //如果上次的暂停时间是有值得，用当前毫秒数减去上次的毫秒数，这样就会得到暂停时间
                           this.pauseTime += (!this.pauseDate ? 0 : new Date().getTime()- this.pauseDate);
                           if(this.time) return;
                           this.time = new Date().getTime();
                           return;//是为bool判断跳出
                       }

                       this.startBn_v="开始";
                       this.pauseDate=new Date().getTime();
                       return;//是为this是否等于startBn判断跳出
                   }
                   else if(buttonType === "restBn"){
                       if(this.showTime_v != "00:00:00"){
                           this.endPress = true
                           save_video_flag = false
                       }
                   }

                   this.startBn_v ="开始";
                   this.pauseTime = 0;
                   this.pauseDate = null;
                   this.bool_flag = false;
                   this.time = 0;
                   this.showTime_v = "00:00:00";
                   this.startPress = false;
               },

               /*开始计时，并提醒后台采集数据*/
               start_pause_collected : async function () {

                   //点击start时将状态提交给后台，提示开始采集数据
                   if(this.startBn_v != "开始" && this.startPress == true){  //正在计时，按键名变为暂停

                       _this = this
                       try{
                           await axios.get("/start/" + this.showTime_v)
                               .then(res => {
                                   _this.music_id = res.data
//                                   console.log(_this.music_id)
                           })
                       }catch(err){
                           console.log(err);
                       }

                       if(this.music_id != ""){

                           var temp = "click" + this.music_id
                           var audio = document.getElementById(temp)
                           //参考[js控制html5 audio的暂停、播放、停止](https://www.cnblogs.com/kingplus/p/5587441.html)
                           if(audio!==null) {
                               //检测播放是否已暂停.audio.paused 在播放器播放时返回false.
//                        alert(audio.paused);
                               if (audio.paused) {
                                   audio.play();//audio.play();// 这个就是播放
                               } else {
                                   audio.pause();// 这个就是暂停
                               }
                           }
                       }
                   }

                   //点击pause时将状态提交给后台，提示暂停采集数据
                   if(this.startBn_v != "暂停"){  //暂停计时，按键名变为开始
                       try{
                           axios.get("/pause")
                               .then(res => {})
                       }catch(err){
                           console.log(err);
                       }
                   }
               },

               /**点击endBn时将状态提交给后台，提示停止数据采集并进行数据保存**/
               end_collected : async function () {

                   if(this.endPress == true){

                       var result,xs,ys,names
                       _this = this
                       try{
                           await axios.get("/end")
                               .then(res => {
                                result = res.data;
                                result = result.split("_json_");
                                console.log(result)
                                xs = result[0]
                                ys = result[1]
                                names = result[2]
                           })
                       }catch(err){
                           console.log(err);
                       }

                       //绘制折线图
                       xs = xs.replace(new RegExp("&#34;","gm"),"\"")
                       xs = xs.replace(new RegExp("&#39;","gm"),"\'")
                       console.log(xs)
                       this.x_array = JSON.parse(xs);

                       ys = ys.replace(new RegExp("&#34;","gm"),"\"")
                       ys = ys.replace(new RegExp("&#39;","gm"),"\'")
                       console.log(ys)
                       this.y_array = JSON.parse(ys);

                       names = names.replace(new RegExp("&#34;","gm"),"\"")
                       names = names.replace(new RegExp("&#39;","gm"),"\'")
                       console.log(names)
                       this.names = JSON.parse(names);

                       this.lineChart_plot(this.x_array,this.y_array,this.names)
                       alert("数据采集完毕")
                       $('#myModal').modal('show');

                   }

                   //将js的beat_table变量置为[]
                   beat_startT = []
                   beat_key = []
                   beat_resKey = []
                   beat_resT = []
                   this.endPress = false
               },

               lineChart_plot : function(x_array,y_array,names){

                   var lineDiv = document.getElementById('line-chart');

                   var data = [];
                   for(i = 0; i < y_array.length; ++i){
                       var traceA = {
                           x: x_array[i],
                           y: y_array[i],
                           type: 'scatter',
                           name: names[i]
                       };

                       data.push(traceA)
                   }

                   var layout = {

                   };

                   Plotly.newPlot( lineDiv, data, layout);
               },

               /**点击指定按钮，播放指定提示音*/
               music_clickPlay : function(music_id){
//                    alert(music_id)
                   var audio = document.getElementById(music_id)
                   //参考[js控制html5 audio的暂停、播放、停止](https://www.cnblogs.com/kingplus/p/5587441.html)
                   if(audio!==null) {
                       //检测播放是否已暂停.audio.paused 在播放器播放时返回false.
//                        alert(audio.paused);
                       if (audio.paused) {
                           audio.play();//audio.play();// 这个就是播放
                       } else {
                           audio.pause();// 这个就是暂停
                       }
                   }
               },

               /**实时获取疲劳状态*/
               get_FatigueState : async function(){
                   _this = this
                   try{
                       await axios.get("/getFatigue")
                           .then(res => {
                           _this.fatigueState = res.data
//                                   console.log(_this.music_id)
                   })
                   }catch(err){
                       console.log(err);
                   }
               }
           }
       })

    </script>
</body>
</html>